<template>
  <div class="content">
    <div class="scroll-wrap">
      <p @click="payOrderLinkClick" class="pay-order-link">缴费订单</p>
      <div
        v-for="(item,idx) in identity"
        :key="idx"
        class="identity-info"
        :class="{selected:item.key===selected}"
        @click="handleChoose(item)"
      >
        <img :src="item.icon" alt="icon" class="icon" />
        <div class="text">
          <p class="title">
            {{item.name}}
            <span class="tip">({{item.tip}})</span>
          </p>
          <p v-for="(i,j) in item.desc" :key="j" class="desc">{{i}}</p>
        </div>
        <span
          class="tag"
          :class="{hide: isEnd&&item.key!=='ENTITY'}"
          v-if="!item.isAlready"
        >{{item.amount}}</span>
        <span class="tagAlready" v-else>当前身份</span>
      </div>
    </div>
    <button class="btn-action-red" @click="next">确定</button>
  </div>
</template>

<script>
import {
  FIND_SHOP_OPEN_BY_MOBILE,
  FIND_OPEN_SHOP_STATE,
  FIND_OPEN_SHOP_ORDER_INFO,
  FIND_OPEN_SHOP_PAY_MODE
} from '@/api/new-open-shop'
import { FIND_USER_OPEN_ID } from '@/api'

import { getCurrentPageParams, currencyFormatter } from '@/utils/wx-tools'
import { Base64 } from 'js-base64'
export default {
  data () {
    return {
      selected: 'ENTITY', // 选中开店类型
      hasShop: false, // 是否已经开过店
      isUnderReview: false, // 开店是否正在审核
      hasPaid: 'N', // 是否已经支付
      payModeList: [], // 开店类型配置
      paidType: null, // 已经支付的开店类型
      isEnd: false, // 是否已经开了实体店
      shopState: 0, // 店铺状态，0表示未通过，等效于未开店
      openState: 'OPEN'
    }
  },
  onShow () {
    this.init()
    this.getwxCode()
    this.findShopOpend()
    this.findShopPayMode()
  },
  computed: {
    identity () {
      let l1 = [
        {
          name: '实业宝',
          key: 'ENTITY',
          icon:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/shitione@3x.png',
          iconActive:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/shiti@3x.png',
          tip: '必须要求有营业执照',
          desc: ['开通线上微商城+线下收款二维码'],
          amount: this.calcPayAmount('ENTITY'),
          isAlready: getCurrentPageParams('identity') === 'ENTITY'
        }
      ]
      let l2 = [
        {
          name: '网商宝',
          key: 'VIRTUAL',
          icon:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/wnaghongong@3x.png',
          iconActive:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/wanghong@3x.png',
          tip: '自然人可开通使用',
          desc: ['开通线上体验微商城+线下收款', '二维码+增值服务推广赚钱'],
          amount: this.calcPayAmount('VIRTUAL'),
          isAlready: getCurrentPageParams('identity') === 'VIRTUAL'
        }
      ]
      let l3 = [
        {
          name: '创业宝',
          key: 'PERSONAL',
          icon:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/gerenshangjai@3x.png',
          iconActive:
            'https://akk.028wkf.cn/kdb-weapp-img/new-open-shop/geren@3x.png',
          tip: '自然人可开通使用',
          desc: ['线上微商城+销售商入驻分销赚钱'],
          amount: this.calcPayAmount('PERSONAL'),
          isAlready: getCurrentPageParams('identity') === 'PERSONAL'
        }
      ]

      let list = []

      if (getCurrentPageParams('LinkIdentity')) {
        if (getCurrentPageParams('identity') === 'ENTITY') {
          list = l1
        } else if (getCurrentPageParams('identity') === 'VIRTUAL') {
          list = l1.concat(l2)
        } else {
          list = l1.concat(l2).concat(l3)
        }
      } else {
        list = l1.concat(l2).concat(l3)
      }

      return list.map(_ => ({
        ..._,
        icon: _.key === this.selected ? _.iconActive : _.icon
      }))
    }
  },
  methods: {
    payOrderLinkClick () {
      this.$router.push('/pages/new-open-shop/order/main')
    },

    handleChoose (item) {
      this.selected = item.key
    },

    next () {
      if (this.selected === getCurrentPageParams('identity')) {
        this.$toast('当前身份不能升级')
        return false
      }
      if (getCurrentPageParams('identity')) {
        let mode = this.payModeList.find(_ => _.shopIdentity === this.selected)
        let realHasPaid =
          this.hasPaid === 'Y' && this.shopState !== 0 ? 'Y' : 'N'
        this.$cookie.set('open-shop-has-paid', realHasPaid)

        if (realHasPaid === 'N' && mode.amount) {
          this.$cookie.set('openShopOrderNo', '')
        }

        this.$cookie.set('openShopIdentity', this.selected)

        this.$router.push(
          `/pages/new-open-shop/introduction/main?identity=${
            this.selected
          }&amount=${mode.amount}`
        )
        return false
      }

      if (this.hasShop) {
        if (this.isUnderReview) {
          this.$toast('您的店铺正在审核中')
        } else {
          this.$toast('您的账号已开店')
        }
        return false
      } else if (
        this.hasPaid === 'Y' &&
        this.selected !== this.paidType &&
        this.shopState !== 0
      ) {
        this.$toast('暂时不能申请其他类型')
        return false
      }

      let mode = this.payModeList.find(_ => _.shopIdentity === this.selected)
      let realHasPaid = this.hasPaid === 'Y' && this.shopState !== 0 ? 'Y' : 'N'
      this.$cookie.set('open-shop-has-paid', realHasPaid)

      if (realHasPaid === 'N' && mode.amount) {
        this.$cookie.set('openShopOrderNo', '')
      }

      this.$cookie.set('openShopIdentity', this.selected)

      this.$router.push(
        `/pages/new-open-shop/introduction/main?identity=${
          this.selected
        }&amount=${mode.amount}`
      )
    },

    /* format */
    calcPayAmount (type) {
      if (
        type === this.paidType &&
        this.hasPaid === 'Y' &&
        this.shopState !== 0
      ) {
        return '已缴费'
      }

      let mode = this.payModeList.find(_ => _.shopIdentity === type)
      if (mode && mode.amount > 0) {
        return currencyFormatter(mode.amount, 0.01)
      } else {
        return '免费'
      }
    },

    /* api */
    findShopOpend () {
      const vm = this

      let mobile =
        vm.$cookie.get('store-mobile') || vm.$cookie.get('account').cellphone
      let providerId = vm.$store.state.account.providerId

      FIND_SHOP_OPEN_BY_MOBILE(providerId, mobile)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.shopId) {
              vm.hasShop = r.data.data.state !== 0
              vm.findShopState()
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    findShopState () {
      const vm = this

      let customerId = getCurrentPageParams('customerId')
      let providerId = vm.$store.state.account.providerId

      FIND_OPEN_SHOP_STATE(providerId, customerId)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data) {
              const { state } = r.data.data
              vm.isUnderReview = state === -1
              vm.shopState = state
            }
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    findShopPayMode () {
      const vm = this

      if (getCurrentPageParams('openShopOrderNo')) {
        return false
      }

      let customerId = getCurrentPageParams('customerId')
      let providerId = vm.$store.state.account.providerId || getCurrentPageParams('providerId')
      vm.$cookie.set('upgrade-shop-customerId', customerId)
      let params = {
        providerId: providerId,
        customerId: customerId,
        openShopType: vm.openState
      }
      if (vm.$cookie.get('IS-UPGRADE')) {
        params.shopIdentity = vm.selected
      }

      FIND_OPEN_SHOP_PAY_MODE(params)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data) {
              const { isPay, openShopList, openShopOrderNo } = r.data.data

              vm.payModeList = openShopList
              vm.hasPaid = isPay
              vm.$cookie.set('openShopOrderNo', openShopOrderNo || '')

              if (isPay === 'Y') {
                vm.findShopPaidInfo()
              }
            }
          } else if (r.data.code === 'ORDER-STATE-ERROR') {
            // 不可再开店
            vm.hasPaid = 'Y'
            vm.paidType = 'ENTITY'
            vm.isEnd = true
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    findShopPaidInfo () {
      const vm = this

      const orderNo =
        getCurrentPageParams('openShopOrderNo') ||
        vm.$cookie.get('openShopOrderNo')

      FIND_OPEN_SHOP_ORDER_INFO(orderNo)
        .then(r => {
          if (r.data.code === '0') {
            vm.paidType = r.data.data.shopIdentity
            vm.shopState = r.data.data.state
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    getwxCode () {
      const vm = this
      wx.login({
        timeout: 6000,
        success: function (res) {
          vm.$cookie.set('code', res.code)
          vm._getOpenId()
        },
        fail: function (err) {
          console.error(err)
        }
      })
    },
    _getOpenId () {
      const vm = this
      if (vm.$cookie.get('openId')) {
        return false
      }
      let appSecret = Base64.decode(vm.$store.state.appSecret)
      FIND_USER_OPEN_ID(
        vm.$store.state.appId,
        appSecret,
        vm.$cookie.get('code')
      )
        .then(r => {
          // console.log(r.data)
          vm.loading = false
          if (r.data.code === '0') {
            vm.$cookie.set('openId', r.data.data)
          } else {
            vm.$cookie.remove('code')
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          vm.loading = false
          console.error(e)
        })
    },
    init () {
      const vm = this
      vm.$cookie.remove('openShopIdentity')
      vm.hasShop = false
      vm.isUnderReview = false
      vm.hasPaid = 'N'
      vm.payModeList = []
      vm.paidType = null
      vm.isEnd = false
      vm.shopState = 0
      if (getCurrentPageParams('LinkIdentity')) {
        vm.$cookie.set('IS-UPGRADE', true)
        vm.openState = 'UPGRADE'
      } else {
        vm.$cookie.remove('IS-UPGRADE')
        vm.openState = 'OPEN'
      }
      // if (vm.$cookie.get('open-shop-has-paid')) {
      //   vm.selected = vm.$cookie.get('open-shop-has-paid')
      // } else {
      //   vm.selected = 'ENTITY'
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
$red: #c13222;
.content {
  height: 100vh;

  .scroll-wrap {
    width: 100%;
    height: calc(100% - 50px);
    background-color: #f6f7f9;
    padding: 10px 15px;
    > .pay-order-link {
      font-size: 14px;
      text-align: right;
      padding: 0 0 10px;
    }
    > .identity-info {
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      background-color: #fff;
      border-radius: 8px;
      border: 1px solid #fff;
      margin-bottom: 10px;
      &.selected {
        border-color: $red;
      }
      > .icon {
        width: 48px;
        height: 48px;
        margin: 15px;
      }
      > .text {
        > .title {
          font-size: 16px;
          color: #606060;
          margin-bottom: 5px;
          > .tip {
            font-size: 14px;
            color: #b2b2b2;
          }
        }
        > .desc {
          font-size: 14px;
          color: #b2b2b2;
        }
      }
      > .tag {
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        background-color: $red;
        color: #fff;
        font-size: 8px;
        transform: translate(37px, -5px) rotate(40deg);
        width: 100px;
        height: 30px;
        line-height: 40px;
        text-align: center;
        &.hide {
          opacity: 0;
        }
      }
      > .tagAlready {
        display: block;
        position: absolute;
        top: 5px;
        right: 5px;
        font-size: 13px;
        line-height: 13px;
        padding: 4px;
        border: 1px solid #409eff;
        border-radius: 4px;
        color: #409eff;
      }
    }
  }
}
</style>

